/* 
 * @Author: 21克的爱情
 * @Date: 2020-04-27 16:42:06
 * @Email: raohong07@163.com
 * @LastEditors: 21克的爱情
 * @LastEditTime: 2020-10-05 15:39:29
 * @Description: 电影搜索页面
 */

import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:ki5k_video/resources/ThemeUtils.dart';
import 'package:ki5k_video/utils/sqflite/SQliteHelp.dart';
import 'package:ki5k_video/utils/sqflite/SQliteMessage.dart';
import 'package:provider/provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:xml/xml.dart';
import 'dart:async';
import 'dart:io';

import '../../api/Api.dart';
import '../../models/video_attr.dart';
import 'video/video_detail_page.dart';
import '../../provide/application_provide.dart';

class SearchVideoPage extends StatefulWidget {
  SearchVideoPage({Key key}) : super(key: key);

  @override
  _SearchVideoPageState createState() => _SearchVideoPageState();
}

class _SearchVideoPageState extends State<SearchVideoPage> {
  ScrollController _controller;
  TextEditingController _textController;
  List<VideoSearch> listData=[];
  List<VideoSearch> listSearchData=[];

  bool loadStatus = false;
  int pageIndex = 1;
  String searchStr='';
  @override
  void initState() { 
    super.initState();

    initDbData();
    
    if(!mounted) return;
    _controller = new ScrollController();
    _textController = new TextEditingController();

    _controller.addListener(() {
      if(!loadStatus && _controller.position.maxScrollExtent - 200 < _controller.position.pixels){
        setState(() {
          pageIndex ++;
        });
        searchData();
      }
    });
  }

  // 获取搜索记录
  void initDbData() async {
    List data = await SQliteHelp.instance.searchData(SQliteMessage.tableSearch);
    print(data);
    setState(() {
      listSearchData = getVideoSearchList(data);
    });
  }


  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();

    _controller?.dispose();
  }

  // 加载数据
  void searchData() async {
    setState(() {
      loadStatus = true;
    });
    if( searchStr != null && searchStr.isNotEmpty ){
      Api().getHomeVideo({
        'ac': 'list',
        't':'',
        'ids':'',
        'pg': pageIndex,
        'wd': searchStr
      }, index: context.read<ApplicationStatus>().currentIndex).then((value) async {
        if( value != null && value.isNotEmpty ){
          final document = XmlDocument.parse(value);
          var videoData = document.findAllElements('video').toList();
          
          if( videoData != null && videoData.length > 0 ){
            List<VideoSearch> list=[];
            videoData.forEach((node){
              list.add(
                VideoSearch.fromJson({
                  'name': node.findElements('name').single.text,
                  'id': int.parse(node.findElements('id').single.text),
                  'tid': node.findElements('tid').single.text,
                  'type': node.findElements('type').single.text,
                  'last': node.findElements('last').single.text,
                  'note': node.findElements('note').single.text,
                })
              );
            });
            setState(() {
              loadStatus = false;
              listData = list;
            });
          }
        }
      });
    } else {
      setState(() {
        pageIndex = 1;
        listData = [];
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        centerTitle: true,
        titleSpacing: NavigationToolbar.kMiddleSpacing,
        title: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            Expanded(
              child: Container(
                height: ScreenUtil.getInstance().getSp(38),
                decoration: BoxDecoration(
                  color: Colors.black12,
                  borderRadius: BorderRadius.circular(20)
                ),
                child: TextField(
                  controller: _textController,
                  cursorColor: Colors.white,
                  textAlignVertical: TextAlignVertical.bottom,
                  textCapitalization: TextCapitalization.characters,
                  decoration: InputDecoration(
                    hintText: '请输入搜索视频名称',
                    border: OutlineInputBorder(borderSide: BorderSide.none),
                    hintStyle: TextStyle(
                      color: Colors.white70
                    ),
                  ),
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14
                  ),
                  onChanged: (value){
                    setState(() {
                      searchStr = value;
                    });
                  },
                ),
              ),
            ),
            Container(
              width: 50,
              margin: EdgeInsets.only(left: 10),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(20)
              ),
              child: FlatButton(
                padding: EdgeInsets.all(0),
                onPressed: () async {
                  // await SpUtil.getInstance();
                  // List<String> list = SpUtil.getObjList('search', (v) => null);
                  // list.add(searchStr);
                  // SpUtil.putObjectList('search', list);
                  if(searchStr.isNotEmpty){
                    await SQliteHelp.instance.searchVideoName(searchStr);
                  }
                  initDbData();
                  searchData();
                },
                child: Text(
                  '搜索',
                  style: TextStyle(
                    color: Colors.white
                  )
                ),
              )
            )
          ],
        ),
      ),
      body: listData.length > 0 ? ListView.builder(
        itemCount: listData.length,
        controller: _controller,
        itemBuilder: (BuildContext context, int index){
          return InkWell(
            onTap: (){
              Navigator.of(context).push(
                MaterialPageRoute(builder: (_){
                  return VideoDetailPage( listData[index].id );
                })
              );
            },
            child: Container(
              margin: EdgeInsets.symmetric(
                vertical: 10,
                horizontal: 10
              ),
              padding: EdgeInsets.symmetric(
                vertical: 10,
                horizontal: 10
              ),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(10))
              ),
              child: Column(
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Expanded(
                        child: Text(
                          '${listData[index].name}',
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      Text('${listData[index].note.length < 8 ? listData[index].note : listData[index].note.substring(0,8)}'),
                    ],
                  ),
                  SizedBox(height: 10,),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text('${listData[index].last}'),
                      Text('${listData[index].type}'),
                    ],
                  )
                ],
              ),
            ),
          );
        },
      ) : Container(
        padding: EdgeInsets.symmetric(
          horizontal: 10,
        ),
        child: Column(
          children: [
            Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text('历史记录'),
                  Transform.scale(
                    scale: 0.7,
                    alignment: Alignment.centerRight,
                    child: RaisedButton(
                      textColor: ThemeUtils.mainBtnDisColor,
                      color: Colors.black26,
                      padding: EdgeInsets.all(0),
                      elevation: 0,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(40)),
                      ),
                      onPressed: () async {
                        await SQliteHelp.instance.cleanData(SQliteMessage.tableSearch);
                        initDbData();
                      }, 
                      child: Text('清除'),
                    ),
                  ),
                ],
              ),
            ),
            Container(
              alignment: Alignment.centerLeft,
              child: Wrap(
                spacing: 10,
                direction: Axis.horizontal,
                children: listSearchData.map((item){
                  return InkWell(
                    onTap: (){
                      _textController.text = item.name;
                      setState(() {
                        searchStr = item.name;
                      });
                    },
                    child: Container(
                      margin: EdgeInsets.only(
                        top: 10
                      ),
                      padding: EdgeInsets.symmetric(
                        vertical: 5,
                        horizontal: 10
                      ),
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Colors.grey[300]
                        ),
                        borderRadius: BorderRadius.circular(5)
                      ),
                      child: Text('${item.name}')
                    )
                  );
                }).toList()
              )
            )
          ],
        )
      ),
    );
  }
}